package devyouk.util.excel.listener;

import devyouk.util.excel.ColumnConfig;
import devyouk.util.excel.ExcelBuilder.OnCreateStyle;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import devyouk.util.excel.cellAdapter.CellValueAdapter;

import javax.validation.constraints.NotNull;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

public class DefaultDataStyleListener implements OnCreateStyle {

    private CellValueAdapter cellAdapter;

    public void setAdapter(@NotNull CellValueAdapter cellAdapter) {
        this.cellAdapter = cellAdapter;
    }

    private HashMap<Class, CellStyle> styleMap = new HashMap<>();
    @Override
    public CellStyle onCreate(Workbook workbook, ColumnConfig columnConfig) {
        CellValueAdapter adapter = columnConfig.getCellValueAdapter();
        adapter = adapter == null ? cellAdapter : adapter;
        CellStyle style = styleMap.get(adapter.getCellValueType());
        if (style == null) {
            style = createDataTypeStyle(workbook, adapter);
            styleMap.put(adapter.getCellValueType(), style);
        }
        return style;
    }

    protected CellStyle createDataTypeStyle(Workbook workbook, CellValueAdapter adapter) {
        CellStyle defaultStyle = createDefaultStyle(workbook);
        Class type = adapter.getCellValueType();
        if (type == Double.class) {
            // 4 位小数 excel 会计格式
            short format = workbook.createDataFormat().getFormat("_ * #,##0.0000_ ;_ * -#,##0.0000_ ;_ * \"-\"????_ ;_ @_ ");
            defaultStyle.setDataFormat(format);
        } else if (type == Date.class || type == Calendar.class) {
            // yyyy-MM-dd
            short format = workbook.createDataFormat().getFormat("yyyy-mm-dd;@");
            defaultStyle.setDataFormat(format);
        } else {
            // string 不需要设置格式
        }
        return defaultStyle;
    }

    protected CellStyle createDefaultStyle(Workbook workbook) {
        CellStyle defaultStyle = workbook.createCellStyle();
        defaultStyle.setBorderBottom(BorderStyle.THIN); // 下边框
        defaultStyle.setBorderLeft(BorderStyle.THIN);// 左边框
        defaultStyle.setBorderTop(BorderStyle.THIN);// 上边框
        defaultStyle.setBorderRight(BorderStyle.THIN);// 右边框
        defaultStyle.setAlignment(HorizontalAlignment.CENTER);//居中显示
        return defaultStyle;
    }
}
